package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;

    //分页查询
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> list = checkGroupDao.findPage(queryString);
        return new PageResult(list.getTotal(), list.getResult());
    }

    //添加
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.add(checkGroup);
        setGroupAndItem(checkGroup.getId(), checkitemIds);

    }

    //根据id查找
    @Override
    public CheckGroup findById(Integer id) {
        System.out.println(id+"======================================================================");
        return checkGroupDao.findById(id);
    }

    //关系表查询
    @Override
    public List<Integer> findCheckitemIdsByCheckgroupId(Integer id) {
        return checkGroupDao.findCheckitemIdsByCheckgroupId(id);
    }

    //编辑
    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //清理表与表原来的关系
        checkGroupDao.deleteAssociation(checkGroup.getId());
        //再添加新的关系
        setGroupAndItem(checkGroup.getId(),checkitemIds);
        checkGroupDao.edit(checkGroup);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }


    //设置检查项和检查组之间的关系
    public void setGroupAndItem(Integer checkGroupId, Integer[] checkitemIds) {
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("checkgroup_id", checkGroupId);
                map.put("checkitem_id", checkitemId);
                checkGroupDao.setGroupAndItem(map);
            }
        }
    }
}
